package database;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;

import object.Contract;
import utility.StringUtil;
import clientMain.Login;
import clientMain.Main;

public class ContractDelegate {

	
	public Vector<Contract> getListContract(int page, String sort, boolean flag) {
		Vector<Contract> list = new Vector<Contract>();
		try {
			Login.conn.setAutoCommit(false);
			CallableStatement cst = Login.conn.prepareCall("{ call sp_ListContract(?, ?, ?, ?) }");
			cst.setInt(1, Main.record);
			cst.setInt(2, page);
			cst.setString(3, sort);
			cst.setBoolean(4, flag);
			ResultSet rs = cst.executeQuery();
			while(rs.next()){
				Contract contract = new Contract();
				contract.setContractId(rs.getInt("Contract_Id"));
				contract.setContractName(StringUtil.getFilterIllegal(rs.getString("Contract_Name")));
				if(page !=0){
					contract.setContractDes(StringUtil.getFilterIllegal(rs.getString("Contract_Des")));
				}
				list.add(contract);
			}
			Login.conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			list = null;
		}
		
		return list;
	}
	
	public boolean insertContract(Contract Con,int userInset){
		boolean flag = false;
		try {
		Login.conn.setAutoCommit(false);
		CallableStatement cst = Login.conn.prepareCall("{call sp_InsertContract(?,?,?)}");
		cst.setString(1, StringUtil.setFilterIllegal(Con.getContractName()));
		cst.setString(2, StringUtil.setFilterIllegal(Con.getContractDes()));
		cst.setInt(3, userInset);
		cst.executeUpdate();
		Login.conn.commit();
		flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
	

	public boolean updateContract(Contract Con,int userUpdate){
		boolean flag = false;
		try {
		Login.conn.setAutoCommit(false);
		CallableStatement cst = Login.conn.prepareCall("{call sp_UpdateContract(?,?,?,?)}");
		cst.setInt(1, Con.getContractId());
		cst.setString(2, StringUtil.setFilterIllegal(Con.getContractName()));
		cst.setString(3, StringUtil.setFilterIllegal(Con.getContractDes()));
		cst.setInt(4, userUpdate);
		cst.executeUpdate();
		Login.conn.commit();
		flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
	
	public boolean CheckInsertContractName(String name){
		boolean rs = false;
		try {	
			  Statement st = Login.conn.createStatement();
			  ResultSet  traVe = st.executeQuery("select  * from Contract where Contract_Name  =N'"+name+"'");
			  while (traVe.next()) { 
				  rs = true;
			  }
			  return rs;
			  
		} catch (Exception e) {
			
		}
		return rs;
	}
	

}
